#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Mikan JSON Action

Mikan Python Web Framework
"""

__author__ = "K.Sonohara"
__status__ = "develop"
__version__ = "0.0.0_36"
__date__    = "2014/01/05"
__license__ = 'LGPL'

# ------------------------------------------------------------
## Import Section
# ------------------------------------------------------------
# Python
import traceback

# ESiPC
from esipc import ESiPCProperty
from esipc.util import load_json
from esipc.mail import create_mail, send_mail

# Mikan
from mikan.idt.acidt import MIKAN_IDT_AC
from mikan.exception import MikanSendRedirectException, MikanExceptions, MikanStatusException
from mikan.action import AbstractMikanAction
from mikan.item.attribute import to_value

# ------------------------------------------------------------
## Variable Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Function Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Class Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Mikan JSON アクション 抽象 クラス
#
class AbstractMikanJSONAction(AbstractMikanAction):

	# ----------------------------------------------------
	## Constructor
	#  @param request Request
	#  @param formclass Item form class
	#  @param entityclass Item entity class
	def __init__(self, request):
		super(AbstractMikanJSONAction, self).__init__(request)

#	def perform(self):
#		return True

	# ----------------------------------------------------
	## Property

# ------------------------------------------------------------
## Mikan JSON 引数 アクション 抽象 クラス
#
class MikanJSONLoadAction(AbstractMikanJSONAction):

	# ----------------------------------------------------
	## Constructor
	#  @param request Request
	#  @param formclass Item form class
	#  @param entityclass Item entity class
	def __init__(self, request, file_json):
		super(MikanJSONLoadAction, self).__init__(request)

		self.FFileJSON = file_json

	# ----------------------------------------------------
	## Perform
	# @return True is chain perform
	def perform(self):
		self.FJSON = self.load_json()

		# result & super
		return super(MikanJSONLoadAction, self).perform()

	def get_file_json(self):
		return self.FFileJSON

	def get_json(self):
		return self.FJSON

	def _json_name(self):
		return "name"

	def _json_dict(self, j):
		if j:
			js = {}
			for l in j:
				k = l[self._json_name()]
				js[k] = l
			return js

		return None

	def load_json(self):
		return self._json_dict(load_json(self.file_json)["items"])

	# ----------------------------------------------------
	## Property
	json = ESiPCProperty(get_json, None, None)
	file_json = ESiPCProperty(get_file_json, None, None)

# ------------------------------------------------------------
## Mikan JSON 引数 アクション 抽象 クラス
#
class MikanJSONParamAction(MikanJSONLoadAction):

	# ----------------------------------------------------
	## Constructor
	#  @param request Request
	#  @param formclass Item form class
	#  @param entityclass Item entity class
	def __init__(self, request, file_json):
		super(MikanJSONParamAction, self).__init__(request, file_json)

	# ----------------------------------------------------
	## Perform
	# @return True is chain perform
	def perform(self):
		try:
			if super(MikanJSONParamAction, self).perform():
				for k,v in self.json.items():
					value = self.request.get_param_str(v["name"], None)
					if value != None:
						v["value"] = value
		except Exception, e:
			if self.islogdebug:
				self.logger.debug(traceback.format_exc())
			print (traceback.format_exc())
			if isinstance(e, MikanExceptions):
				self.request.exceptions.extend(e.exceptions)
			else:
				self.request.exceptions.append(e)

		return True

	# ----------------------------------------------------
	## Property

class MikanJSONMailAction(MikanJSONParamAction):

	# ----------------------------------------------------
	## Constructor
	#  @param parent Parent action
	def __init__(self, request, file_json):
		# super
		super(MikanJSONMailAction, self).__init__(request, file_json)
		self.sortkey = 99999

	def get_mail_text(self, json):
		return ""

	def get_mail_title(self, json):
		return ""

	def get_mail_to(self, json):
		return ""

	def get_mail_from(self, json):
		return ""

	def get_mail_bcc(self, json):
		return None

	def send_mail(self, mailfrom, mailto, mail, host=None):
		send_mail(mailfrom, mailto, mail, None)

	# ----------------------------------------------------
	## Perform
	# @return True is chain perform
	def perform(self):
		if super(MikanJSONMailAction, self).perform():
			try:
				# mail param
				mailto = self.get_mail_to(self.json)
				mailbcc = self.get_mail_bcc(self.json)
				mailfrom = self.get_mail_from(self.json)
				mailtitle = self.get_mail_title(self.json)
				mailtext = self.get_mail_text(self.json)

				# create mail
				mail = create_mail(mailtitle, mailtext, mailfrom, mailto, encode="UTF-8")
				if mailbcc:
					mail["Bcc"] = mailbcc

				# log
				if self.islogdebug:
					self.logger.debug(mail)

				# send mail
				if self.request.maildryrun == "0":
					self.send_mail(mailfrom, mailto, mail, host=self.request.mailsmtphost)
				else:
					self.logger.error(unicode(mail))
			except Exception, e:
				if self.islogdebug:
					self.logger.debug(traceback.format_exc())
				if isinstance(e, MikanExceptions):
					self.request.exceptions.extend(e.exceptions)
				else:
					self.request.exceptions.append(e)

		# result & super
		return True

	# ----------------------------------------------------
	## Property

# ------------------------------------------------------------
## Main Section
# ------------------------------------------------------------
if __name__ == '__main__':
	pass

# ------------------------------------------------------------
